package com.neusoft.tools;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;

public class FXMLUtils {
    /**
     * 转换fxml文件，切换场景
     * @param node 触发转换事件的节点，如button
     * @param fxmlPath nep下的路径 eg.NEPS/view/UserRegisterView.fxml
     */
    public static void switchToShow(Node node, String fxmlPath) throws IOException {
        // 使用绝对路径来获取 FXML 文件的 URL
        URL url = FXMLUtils.class.getResource("/com/neusoft/nep/" + fxmlPath);
        // 空值检查
        if (url == null) {
            throw new IOException("无法找到指定的 FXML 文件: /com/neusoft/nep/" + fxmlPath);
        }

        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(url);
        Scene scene = node.getScene();
        scene.setRoot(fxmlLoader.load());
        Stage stage = (Stage) scene.getWindow();
        stage.setScene(scene);
        stage.show();
    }
        public static void switchToShowAndKeep(Hyperlink sourceLink, String fxmlPath) throws IOException {
            FXMLLoader fxmlLoader = new FXMLLoader();
            URL location = FXMLUtils.class.getResource("/com/neusoft/nep/" + fxmlPath);
            if (location == null) {
                throw new IOException("找不到 FXML 文件：" + "/com/neusoft/nep/" + fxmlPath);
            }
            fxmlLoader.setLocation(location);
            Parent newRoot = fxmlLoader.load();

            //让场景自动适配内容
            Scene newScene = new Scene(newRoot);

            newRoot.applyCss();
            newRoot.layout();

            Stage stage = (Stage) sourceLink.getScene().getWindow();
            stage.setScene(newScene);
            //为了保证stage与scene的大小相契合
            stage.sizeToScene();
        }
}
